<template>
  <div v-if="user.admin" class="flex">
    <el-button size="mini" @click="operateSpace('recommend')" :loading="isLoading.recommend"
               :type="recommendBtn.type">{{ recommendBtn.label }}</el-button>
    <el-button size="mini" @click="operateSpace('top')" :loading="isLoading.top"
               :type="topBtn.type">{{ topBtn.label }}</el-button>
    <el-button size="mini" @click="operateSpace('public')" :loading="isLoading.public"
               :type="publicBtn.type">{{ publicBtn.label }}</el-button>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import * as spaceFormat from '../format';

export default {
  name: 'OperateButtons', // 一些管理员快捷操作空间的按钮
  data() {
    return {
      isLoading: {
        recommend: false,
        top: false,
        public: false,
      },
    };
  },
  computed: {
    ...mapState({ space: 'currentSpace', user: 'currentUser' }),
    recommendBtn() {
      if (this.space.recommend) return { label: '取消推荐', type: 'warning' };
      return { label: '推荐空间', type: 'success' };
    },
    topBtn() {
      if (this.space.top) return { label: '取消精品', type: 'warning' };
      return { label: '标记精品', type: 'success' };
    },
    publicBtn() {
      if (this.space.public) return { label: '取消公开', type: 'warning' };
      return { label: '公开空间', type: 'success' };
    },
  },
  methods: {
    ...mapActions(['setCurrentSpace']),
    // 空间管理员设置空间
    operateSpace(type) { // recommend, top
      const msg = `<div>确认${this.initOperateMsg(type)} <strong class="el-alert--warning is-light is-bold">${this.space.title}</strong> 吗？</div>`;
      this.$confirm(msg, '确认操作', {
        dangerouslyUseHTMLString: true,
        customClass: 'confirm-left',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.isLoading[type] = true;
        this.$api.spaces.operate({
          spaceId: this.space.id,
          type,
          value: !this.space[type],
        }).then((res) => {
          this.$message.success('设置成功');
          this.setCurrentSpace(spaceFormat.formatSpace(res.data));
        }).catch(() => {})
          .then(() => { this.isLoading[type] = false; });
      }).catch(() => {});
    },
    // 生成管理员操作空间的提醒
    initOperateMsg(type) {
      if (type === 'recommend') return this.recommendBtn.label;
      else if (type === 'top') return this.topBtn.label;
      else if (type === 'public') return this.publicBtn.label;
      return '';
    },
  },
};
</script>

<style></style>
